package com.qianxx.base;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.qianxx.draw.R;

@SuppressLint("SetJavaScriptEnabled")
public class BaseWebViewAty extends BaseAty {

	private static final String TAG = BaseWebViewAty.class.getSimpleName();

	public static final String URL_INTENT_KEY = "url";
	public static final String TITLE_INTENT_KEY = "title";
	public static final String HTML_KEY = "html";

	protected LinearLayout loadErrorLayout;
	protected WebView webView;
	protected ProgressBar webviewProgress;
	protected static final String UA = "health";

	protected String url;
	protected String html;

	private Handler hlr;

	protected void setHandler(Handler hlr) {
		this.hlr = hlr;
	}

	private void callback() {
		if (hlr != null) {
			hlr.sendEmptyMessage(0);
		}
	}

	protected void initWebView() {
		initWebView(null);
	}

	protected void initWebView(View parent) {
		if (parent != null) {
			webView = (WebView) parent.findViewById(R.id.web_view);
			loadErrorLayout = (LinearLayout) parent
					.findViewById(R.id.load_error_layout);
			webviewProgress = (ProgressBar) parent
					.findViewById(R.id.webview_progress);
		} else {
			webView = (WebView) findViewById(R.id.web_view);
			loadErrorLayout = (LinearLayout) findViewById(R.id.load_error_layout);
			webviewProgress = (ProgressBar) findViewById(R.id.webview_progress);
		}
		String ua = webView.getSettings().getUserAgentString();
		if (!TextUtils.isEmpty(ua)) {
			ua += UA;
		} else {
			ua = UA;
		}
		webView.getSettings().setUserAgentString(ua);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setBuiltInZoomControls(false);// 设置缩放工具的显示
		webView.setVerticalScrollBarEnabled(false);
		webView.setHorizontalScrollBarEnabled(false);
		webView.setWebChromeClient(webChromeClient);
		webView.setWebViewClient(webClient);

		webView.setVerticalScrollBarEnabled(false);
		webView.setVerticalScrollbarOverlay(false);
		webView.setHorizontalScrollBarEnabled(false);
		webView.setHorizontalScrollbarOverlay(false);

	}

	protected void loadWebData() {
		if (!TextUtils.isEmpty(url)) {
			loadErrorLayout.setVisibility(View.GONE);
//			webView.setVisibility(View.VISIBLE);
			loadWeb(url);
		}
		if (!TextUtils.isEmpty(html)) {
			loadErrorLayout.setVisibility(View.GONE);
//			webView.setVisibility(View.VISIBLE);
			loadWebByDataWithBaseURL(html);
		}
		if (TextUtils.isEmpty(url) && TextUtils.isEmpty(html)) {
			loadWebByDataWithBaseURL("<html></html>");
			// makeToast(R.string.error_web_lading);
//			loadErrorLayout.setVisibility(View.VISIBLE);
//			webView.setVisibility(View.GONE);
		}
	}

	protected void loadWeb(String url) {
		if (webView != null && !TextUtils.isEmpty(url)) {
			synCookies(this, url);
			webView.loadUrl(url);
		}
	}

	protected void loadWebByDataWithBaseURL(String data) {
		webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webView.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
		// 让缩放显示的最小值为起始
		webView.setInitialScale(100);
		// 设置支持缩放
		webView.getSettings().setSupportZoom(true);
		if (webView != null && !TextUtils.isEmpty(data)) {
			webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
		}
	}

	protected void onWebPageFinished(View view, String url) {

	}

	protected void setWebInitialScale(int scale) {
		if (webView != null) {
			webView.setInitialScale(scale);
		}
	}

	protected void setWebUseWideViewPort(boolean use) {
		if (webView != null) {
			webView.getSettings().setUseWideViewPort(use);
		}
	}

	protected void setWebLoadWithOverviewMode(boolean overview) {
		if (webView != null) {
			webView.getSettings().setLoadWithOverviewMode(overview);
		}
	}

	protected void setWebBuiltInZoomControls(boolean enabled) {
		if (webView != null) {
			webView.getSettings().setBuiltInZoomControls(enabled);
		}
	}

	protected void setWebLayoutAlgorithm(LayoutAlgorithm layout) {
		if (webView != null) {
			webView.getSettings().setLayoutAlgorithm(layout);
		}
	}

	@SuppressLint("NewApi")
	protected void setWebDisplayZoomControls(boolean enabled) {
		if (webView != null) {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				webView.getSettings().setDisplayZoomControls(enabled);
			}

		}
	}

	protected void synCookies(Context context, String url) {
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
		// cookieManager.removeSessionCookie();//移除

		// if (DefaultRemoteServiceCall.cookieStore != null
		// && DefaultRemoteServiceCall.cookieStore.getCookies() != null) {
		//
		// List<Cookie> cookies =
		// DefaultRemoteServiceCall.cookieStore.getCookies();
		// for (Cookie cookie : cookies) {
		// String cookieString = cookie.getName() + "=" + cookie.getValue() +
		// "; domain=" + cookie.getDomain();
		// LogUtils.d(TAG, cookieString);
		//
		// cookieManager.setCookie(url, cookieString);
		//
		// CookieSyncManager.getInstance().sync();
		// }
		// }

	}

	protected void setWebCacheModel(int cacheMode) {
		if (webView != null) {
			WebSettings settings = webView.getSettings();
			settings.setCacheMode(cacheMode);
		}
	}

	protected WebChromeClient webChromeClient = new WebChromeClient() {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {

			if (newProgress != 100) {
				webviewProgress.setProgress(newProgress);
			}

			super.onProgressChanged(view, newProgress);
		}

	};

	protected WebViewClient webClient = new WebViewClient() {

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			onWebPageFinished(view, url);
			webviewProgress.setVisibility(View.GONE);
			// LogUtils.d("onPageFinished", url);
			webView.getSettings().setLoadsImagesAutomatically(true);
			// hideProcessingIndicator();
			callback();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			webviewProgress.setVisibility(View.VISIBLE);
			// LogUtils.d("onPageStarted", url);
			webView.getSettings().setLoadsImagesAutomatically(false);
			// showProcessingIndicator();
			super.onPageStarted(view, url, favicon);
		}

		/**
		 * 判断是否是需要过滤的url,是的话,true 表示不处理
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// LogUtils.d(TAG, "shouldOverrideUrlLoading : url = " + url);
			BaseWebViewAty.this.shouldOverrideUrlLoading(view, url);
			webView.loadUrl(url);
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			loadWebByDataWithBaseURL("<html></html>");
			// makeToast(R.string.error_web_lading);
			loadErrorLayout.setVisibility(View.VISIBLE);
//			webView.setVisibility(View.GONE);
			// super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			handler.proceed();
		}
	};

	protected void shouldOverrideUrlLoading(WebView view, String url) {

	}

	protected void onDestroy() {
		// LogUtils.d("result", "webview destory!");
		if (webView != null) {
			webView.getSettings().setBuiltInZoomControls(true);
//			webView.setVisibility(View.GONE);
		}

		super.onDestroy();
	};

	public void loadErrorOnclick(View view) {

	}
}
